<template>
  <div class="cmt-container">
    <hr>
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入要BB的内容(最多BB120字)" maxlength="120" v-model="msg"></textarea>
    <mt-button type='primary' size='large' @click='postComment'>发表评论</mt-button>
    <div class="cmt-list" v-for="(item, i) in comments" :key='item.id'>
      <div class="cmt-item" v-if="i < loadMoreNum">
        <div class="cmt-title">
          {{ i+1 }}楼 {{ item.user_name }}&nbsp;&nbsp;&nbsp;&nbsp;发表时间:{{ item.add_time | dateFormat }}
        </div>
        <div class="cmt-body">
          {{ item.content }}
        </div>
      </div>
    </div>
    <mt-button type='danger' size='large' @click='loadMore' v-show='isShow'>加载更多</mt-button>
  </div>
</template>

<script>
import axios from 'axios'
import { Toast } from 'mint-ui'

export default{
  data () {
    return {
      comments: [],
      loadMoreNum: 10, // 默认显示10条数据
      isShow: true,
      msg: '' // 评论信息
    }
  },
  created () {
    this.getComment()
  },
  methods: {
    getComment () {
      axios.get('http://localhost:8080/api/commentList' + this.id).then(result => {
        if (result.status === 200) {
          this.comments = result.data
          // 小于十条数据不显示加载更多按钮
          // eslint-disable-next-line no-unneeded-ternary
          this.isShow = this.comments.length >= 10 ? true : false
        } else {
          Toast('评论获取失败')
        }
      })
    },
    loadMore () {
      this.loadMoreNum = this.comments.length
      this.isShow = false
    },
    postComment () {
      // 发表评论

      // 校准数据
      if (this.msg.trim().length === 0) {
        return Toast('评论不能为空！')
      }
      // 将数据添加到后台

      // 将数据添加到前台
      var cmt = {
        user_name: '匿名用户',
        add_time: Date.now(),
        content: this.msg.trim(),
        news_id: this.id
      }
      this.comments.unshift(cmt)

      this.msg = ''
    }
  },
  props: ['id']
}
</script>

<style scoped>
  .cmt-container{
    margin:60px 0;
  }
  .cmt-container h3{
    font-size: 16px;
  }
  .cmt-container textarea{
    font-size: 13px;
    height: 85px;
  }
  .cmt-container .cmt-list{
    margin: 5px 0;
    font-size: 13px;
  }
  .cmt-list .cmt-title{
    line-height: 35px;
    background-color: #ccc;
  }
  .cmt-list .cmt-body{
    line-height: 35px;
    text-indent: 2em;
  }
</style>
